TARGET     := SampleAvplayer

TITLE_ID   := AVPLAYER1
TITLE_NAME := Sample Avplayer
APP_VER    := 01.03

APP_NAME_STR := Sample\ Avplayer
APP_VER_STR  := 1.03
APP_DIR_NAME := SampleAvplayer
BUILD_DATE   := $(shell date +"%Y.%m.%d")

VITA_IP := 

MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
MAKEFILE_DIR  := $(dir $(MAKEFILE_PATH))
ROOT_DIR      := $(patsubst %/,%, $(MAKEFILE_DIR))

PKG_DIR       := $(ROOT_DIR)/pkg
BUILD_DIR     := $(ROOT_DIR)/build
SRC_DIR       := $(ROOT_DIR)/src

SRC_C := \
	ctrl_pad.c \
	touch_pad.c \
	avplayer.c \
	avplaylist.c \
	browser.c \
	config.c \
	file.c \
	graphics.c \
	init.c \
	listview.c \
	main.c \
	strnatcmp.c \
	ui.c \
	utils.c

SRC_OBJS := $(SRC_C:.c=.o)

OBJS := $(SRC_OBJS) $(RES_OBJS)
OBJS := $(notdir $(OBJS))
OBJS := $(addprefix $(BUILD_DIR)/, $(OBJS))

LIBS := \
	-lvita2d \
	-lfreetype \
	-lpng \
	-ljpeg \
	-lz \
	-lm \
	-lc \
	-lScePgf_stub \
	-lSceDisplay_stub \
	-lSceGxm_stub \
	-lSceCtrl_stub \
	-lSceTouch_stub \
	-lScePower_stub \
	-lSceAudio_stub \
	-lSceRtc_stub \
	-lSceCommonDialog_stub \
	-lSceSysmodule_stub \
	-lSceAppUtil_stub \
	-lSceAppMgr_stub \
	-lSceShellSvc_stub \
	-lSceAvPlayer_stub

INCDIRS := \
	-ISRC_DIR

DEFINES := \
	-DAPP_NAME_STR=\"$(APP_NAME_STR)\" \
	-DAPP_VER_STR=\"$(APP_VER_STR)\" \
	-DAPP_DIR_NAME=\"$(APP_DIR_NAME)\" \
	-DBUILD_DATE=\"$(BUILD_DATE)\"

WARNINGS := \
	-Wall \
	-Wno-unused-variable \
	-Wno-unused-but-set-variable \
	-Wno-format-truncation

FLAGS += $(WARNINGS) $(INCDIRS) $(DEFINES)
CFLAGS   += -O3 $(FLAGS)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions
LDFLAGS  := -Wl,-q

PREFIX  := arm-vita-eabi
CC      := $(PREFIX)-gcc
CXX     := $(PREFIX)-g++
AS      := $(PREFIX)-as
AR      := $(PREFIX)-ar
OBJCOPY := $(PREFIX)-objcopy
STRIP   := $(PREFIX)-strip
NM      := $(PREFIX)-nm
LD      := $(CXX)

VPK_NAME     := $(TARGET)_v$(APP_VER_STR).vpk
VPK_PATH     := $(ROOT_DIR)/$(VPK_NAME)
EBOOT_PATH   := $(PKG_DIR)/eboot.bin
SFO_PATH     := $(PKG_DIR)/sce_sys/param.sfo

all: create_dir build-vita

build-vita: $(EBOOT_PATH) $(SFO_PATH)
	@rm -rf $(VPK_PATH)
	cd $(PKG_DIR) && zip -r $(VPK_PATH) ./*

$(SFO_PATH):
	vita-mksfoex -s APP_VER="$(APP_VER)" \
		-s TITLE_ID="$(TITLE_ID)" "$(TITLE_NAME)" \
		-d ATTRIBUTE2=12 $@

$(EBOOT_PATH): $(BUILD_DIR)/$(TARGET).velf
	vita-make-fself -c -a 0x2800000000000001 $< $@

$(BUILD_DIR)/$(TARGET).velf: $(BUILD_DIR)/$(TARGET).elf
	$(STRIP) -g $<
	vita-elf-create $< $@

$(BUILD_DIR)/$(TARGET).elf: $(OBJS)
	$(LD) $(LDFLAGS) $(LIBDIRS) $^ $(LIBS) -o $@

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c
	$(CC) -c $(CFLAGS) $< -o $@

create_dir:
	@mkdir -p $(BUILD_DIR)
	@mkdir -p $(dir $(SFO_PATH))

clean: clean-vita

clean-vita:
	rm -rf $(VPK_PATH) $(EBOOT_PATH) $(SFO_PATH) $(BUILD_DIR) $(OBJS)

vpksend: $(VPK_PATH)
	curl -T $(VPK_PATH) ftp://$(VITA_IP):1337/ux0:/
	@echo "Sent."

send: $(EBOOT_PATH)
	curl -T eboot.bin ftp://$(VITA_IP):1337/ux0:/app/$(TITLE_ID)/
	@echo "Sent."
